#!/usr/bin/env bash

MASON_COMMAND=$1 ; shift
MASON_NAME=$1 ; shift
MASON_VERSION=$1 ; shift

set -eu
set -o pipefail

MASON_RELEASED_VERSION="0.20.0"

if [ "${MASON_COMMAND}" = "--version" ]; then
    echo ${MASON_RELEASED_VERSION}
    exit 0
fi

function usage {
    echo "Usage: $0 <command> <lib> <version>"
}

if [ -z "${MASON_COMMAND}" ]; then
    usage
    exit 1
fi

if [ -z "${MASON_DIR:+isset}" ]; then
    MASON_DIR=$(
        cd "$(dirname "${BASH_SOURCE}")" &&
        if [ -L mason ]; then
            possibly_relative_path=$(readlink mason) &&
            cd "$(dirname "${possibly_relative_path}")"
        fi &&
        pwd
    )
fi

if [ "${MASON_COMMAND}" = "env" ]; then
    . ${MASON_DIR}/mason.sh > /dev/null
    eval echo \$${MASON_NAME}
    exit
fi

if [ -z "${MASON_NAME}" ]; then
    usage
    echo "Missing <lib>"
    exit 1
elif [ -z "${MASON_VERSION}" ]; then
    usage
    echo "Missing <version>"
    exit 1
fi

if [ "${MASON_COMMAND}" = "trigger" ]; then
    if [ -z "${MASON_TRAVIS_TOKEN}" ]; then
        echo "MASON_TRAVIS_TOKEN is not set."
        exit 1
    fi

    config=$(ruby <<RUBY
    require 'yaml'
    require 'json'
    config = YAML.load_file("scripts/${MASON_NAME}/${MASON_VERSION}/.travis.yml")
    config["env"] ||= {}
    config["env"]["global"] ||= []
    config["env"]["global"] << "MASON_NAME=${MASON_NAME}" << "MASON_VERSION=${MASON_VERSION}"
    puts JSON.pretty_generate(config)
RUBY
    )

    body="{
      \"request\": {
        \"message\": \"Building ${MASON_NAME} ${MASON_VERSION}\",
        \"branch\": \"$(git rev-parse --abbrev-ref HEAD)\",
        \"config\": ${config}
      }
    }"

    curl -s -X POST https://api.travis-ci.org/repo/mapbox%2Fmason/requests \
        -H "Content-Type: application/json" \
        -H "Accept: application/json" \
        -H "Travis-API-Version: 3" \
        -H "Authorization: token ${MASON_TRAVIS_TOKEN}" \
        -d "$body"

    echo "Now go to https://travis-ci.org/mapbox/mason/builds to view build status"

    exit
fi

. ${MASON_DIR}/mason.sh

export MASON_DIR
if [ -d "${MASON_DIR}/scripts/${MASON_NAME}/${MASON_VERSION}-${MASON_PLATFORM_VERSION}" ]; then
    bash "${MASON_DIR}/scripts/${MASON_NAME}/${MASON_VERSION}-${MASON_PLATFORM_VERSION}/script.sh" "${MASON_COMMAND}" "$@"
else
    bash "${MASON_DIR}/scripts/${MASON_NAME}/${MASON_VERSION}/script.sh" "${MASON_COMMAND}" "$@"
fi
